package com.cn.jinl.service;

import com.cn.jinl.api.IPhotovoltaicManageService;
import com.cn.jinl.dao.PhotovoltaicManageMapper;
import com.cn.jinl.domain.PhotovoltaicManage;
import com.cn.jinl.domain.PhotovoltaicManageExample;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.NumberUtil;
import com.cn.jinl.utils.QueryForm;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created On : 2024/1/18.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: PhotovoltaicManageServiceImpl
 */
@Service
public class PhotovoltaicManageServiceImpl implements IPhotovoltaicManageService {

    @Autowired
    private PhotovoltaicManageMapper photovoltaicManageMapper;


    @Override
    public List<PhotovoltaicManage> getPhotovoltaicList(QueryForm queryForm) throws Exception {
        List<PhotovoltaicManage> list = photovoltaicManageMapper.getPhotovoltaicList(queryForm);
        this.generateSelfUseRate(list);
        for (PhotovoltaicManage photovoltaicManage:list){
            photovoltaicManage.setMonthDay(this.getTwoNum(photovoltaicManage.getRecordMonth())+"-"+this.getTwoNum(photovoltaicManage.getRecordDay()));
        }
        return list;
    }

    @Override
    public Map<String, Object> getPhotovoltaicStatistics(QueryForm queryForm) throws Exception {

        Map<String,Object> map = Maps.newHashMap();

        //求每年总和 发电量  CO2  等效绿植  自用电量 余电电量
        List<PhotovoltaicManage> sumDataList = photovoltaicManageMapper.getSumDataList();
        this.generateSelfUseRate(sumDataList);

        //求每年发电最高月
        List<PhotovoltaicManage> maxMonthGenerateList = photovoltaicManageMapper.getMaxMonthGenerateList();
        //求每年发电最高日
        List<PhotovoltaicManage> maxMonthDayGenerateList = photovoltaicManageMapper.getMaxMonthDayGenerateList();

        for (PhotovoltaicManage item:sumDataList){

            String maxGenerateMonths = "";
            String maxGenerateDays = "";

            for (PhotovoltaicManage month : maxMonthGenerateList){
                if (item.getRecordYear().equals(month.getRecordYear())){
                    maxGenerateMonths = maxGenerateMonths+month.getRecordMonth()+"月 ";
                }
            }

            for (PhotovoltaicManage monthsDays : maxMonthDayGenerateList){
                monthsDays.setMonthDay(this.getTwoNum(monthsDays.getRecordMonth())+"-"+this.getTwoNum(monthsDays.getRecordDay()));
                if (item.getRecordYear().equals(monthsDays.getRecordYear())){
                    maxGenerateDays = maxGenerateDays+monthsDays.getMonthDay()+" ";
                }
            }

            item.setMaxGenerateMonths(maxGenerateMonths);
            item.setMaxGenerateDays(maxGenerateDays);
        }
        map.put("list",sumDataList);


        //已用年数
        String usedYear = this.generateUsedYear(queryForm.getStartTime());
        map.put("usedYear",usedYear);

        //页面下方弧度图
        List<PhotovoltaicManage> currentYearMonthSum = photovoltaicManageMapper.getCurrentYearSumMonthGenerate(queryForm);
        for (PhotovoltaicManage item : currentYearMonthSum){
            item.setRecordMonth(item.getRecordMonth()+"月");
        }
        map.put("monthDataList",currentYearMonthSum);


        return map;
    }

    @Override
    public String addPhotovoltaic(PhotovoltaicManage photovoltaicManage) throws Exception {

        if (null == photovoltaicManage){
            return "请添加光伏数据";
        }

        String result = this.photovoltaicLeagal(photovoltaicManage);
        if (!"".equals(result)){
            return result;
        }

        int count = 0;
        //determine if the record is duplicated
        synchronized (PhotovoltaicManage.class){
            count = this.countRecord(photovoltaicManage,"");
            if (count > 0){
                return "当前日期已插入数据";
            }

            photovoltaicManage.setId(CommonUtil.generateRandomNum("photovoltaic_"));
            photovoltaicManage.setStatus(Constants.NORMAL_STATUS);
            count = photovoltaicManageMapper.insert(photovoltaicManage);

            if (count < 1){
                throw new Exception("插入数据异常！");
            }
        }

        return "";
    }

    @Override
    public Map<String, Object> bigBordPhotovoltaicData() throws Exception {

        Map<String,Object> map = Maps.newHashMap();

        //等效绿植  累计减排  光伏发电量
        PhotovoltaicManage photovoltaicManage = photovoltaicManageMapper.getAllSumData();
        String sumPlant = photovoltaicManage.getEquivalentPlant();
        String sumCo2 = photovoltaicManage.getCo2();
        String sumGenerate = photovoltaicManage.getPowerGeneration();
        map.put("sumPlant",sumPlant);
        map.put("sumCo2",sumCo2);
        map.put("sumGenerate",sumGenerate);

        //光伏发电量---本年
        //光伏发电量---本月
        String thisYearSumGenerate = photovoltaicManageMapper.countThisYear() == 0 ? "0" : photovoltaicManageMapper.sumThisYearSumGenerate().getPowerGeneration();
        String thisMonthSumGenerate = photovoltaicManageMapper.countThisMonth() == 0? "0" : photovoltaicManageMapper.sumThisMonthSumGenerate().getPowerGeneration();
        map.put("thisYearSumGenerate", thisYearSumGenerate);
        map.put("thisMonthSumGenerate", thisMonthSumGenerate);

        //最高发电日
        List<PhotovoltaicManage> maxGenerateDayList = photovoltaicManageMapper.getMaxGenerateDayList();
        String maxGenerateDay = "";
        for (PhotovoltaicManage item : maxGenerateDayList){
            maxGenerateDay = maxGenerateDay+item.getRecordYear()+"-"+item.getRecordMonth()+"-"+item.getRecordDay()+" ";
        }
        map.put("maxGenerateDay",maxGenerateDay);

        //最高发电月
        List<PhotovoltaicManage> maxGenerateMonthList = photovoltaicManageMapper.getMaxGenerateMonthList();
        String maxGenerateMonth = "";
        for (PhotovoltaicManage item : maxGenerateMonthList){
            maxGenerateMonth = maxGenerateMonth+item.getRecordYear()+"年 "+item.getRecordMonth()+"月 ";
        }
        map.put("maxGenerateMonth", maxGenerateMonth);


        return map;
    }

    @Override
    public String updatePhotovoltaic(PhotovoltaicManage photovoltaicManage) throws Exception {

        String id = photovoltaicManage.getId();

        if (StringUtils.isEmpty(id)){
            return "id is null";
        }

        String result = this.photovoltaicLeagal(photovoltaicManage);
        if (!"".equals(result)){
            return result;
        }

        PhotovoltaicManageExample example = new PhotovoltaicManageExample();
        example.createCriteria().andIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);

        int count = photovoltaicManageMapper.updateByExample(photovoltaicManage,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public PhotovoltaicManage getTodayPhotovoltaicManage() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String yearDay = simpleDateFormat.format(new Date());
        String year = yearDay.split("-")[0];
        String moth = yearDay.split("-")[1];
        String day = yearDay.split("-")[2];
        PhotovoltaicManageExample example = new PhotovoltaicManageExample();
        example.createCriteria().andRecordYearEqualTo(year).andRecordMonthEqualTo(moth).andRecordDayEqualTo(day);
        List<PhotovoltaicManage> photovoltaicManageList = photovoltaicManageMapper.selectByExample(example);
        if(photovoltaicManageList.size() == 0){
            PhotovoltaicManage returnManage = new PhotovoltaicManage();
            returnManage.setPowerGeneration("0");
            returnManage.setEquivalentPlant("0");
            returnManage.setCo2("0");
        }
        return photovoltaicManageList.get(0);
    }


    private String photovoltaicLeagal(PhotovoltaicManage photovoltaicManage){

        String result = "";

        if (StringUtils.isBlank(photovoltaicManage.getCo2())){
            result = "请输入CO2减排（吨）";
            return result;
        }


        if (StringUtils.isBlank(photovoltaicManage.getEquivalentPlant())){
            result = "请输入等效绿植（棵）";
            return result;
        }

        if (StringUtils.isBlank(photovoltaicManage.getSelfConsumption())){
            result = "请输入自用电量（MWh）";
            return result;
        }

        if (StringUtils.isBlank(photovoltaicManage.getPowerSurplus())){
            result = "请输入余电电量（MWh）";
            return result;
        }

        if (StringUtils.isBlank(photovoltaicManage.getPowerGeneration())){
            result = "请输入日发电量（MWh）";
            return result;
        }

        if (!CommonUtil.isNumber(photovoltaicManage.getPowerGeneration()) || !CommonUtil.isNumber(photovoltaicManage.getCo2()) || !CommonUtil.isNumber(photovoltaicManage.getEquivalentPlant()) || !CommonUtil.isNumber(photovoltaicManage.getSelfConsumption()) || !CommonUtil.isNumber(photovoltaicManage.getPowerSurplus())){
            result = "输入参数有误！";
            return result;
        }

        return result;
    }

    private void generateSelfUseRate(List<PhotovoltaicManage> photovoltaicManages) throws Exception{
        for (PhotovoltaicManage photovoltaicManage : photovoltaicManages){

            double selfUseRate = 0;
            if(Double.parseDouble(photovoltaicManage.getPowerGeneration()) == 0){
                selfUseRate = 0;
            } else {
                selfUseRate = Double.parseDouble(photovoltaicManage.getSelfConsumption()) / Double.parseDouble(photovoltaicManage.getPowerGeneration())*100;
            }
            String selfUseRateStr = NumberUtil.getPoint(selfUseRate,2);
            photovoltaicManage.setSelfUseRate(selfUseRateStr+"%");
        }
    }

    private int countRecord(PhotovoltaicManage photovoltaicManage,String id) {
        PhotovoltaicManageExample example = new PhotovoltaicManageExample();
        PhotovoltaicManageExample.Criteria criteria = example.createCriteria();

        criteria.andStatusEqualTo(Constants.NORMAL_STATUS).andRecordYearEqualTo(photovoltaicManage.getRecordYear()).andRecordMonthEqualTo(photovoltaicManage.getRecordMonth()).andRecordDayEqualTo(photovoltaicManage.getRecordDay());
        if (StringUtils.isNotEmpty(id)){
            criteria.andIdEqualTo(id);
        }

        int count = photovoltaicManageMapper.countByExample(example);
        return count;
    }

    private String getTwoNum(String num){
        int parsedNum = Integer.parseInt(num);
        String numStr = parsedNum < 10 ? ("0"+num):num;
        return numStr;
    }

    private String generateUsedYear(String startTime) throws Exception{
        long timestamp = new Date().getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date time = simpleDateFormat.parse(startTime);
        double stamp = (timestamp - time.getTime())/(1000.0*24.0*3600.0*365.0);
        String usedYear = NumberUtil.getPoint(stamp,1);
        if (StringUtils.equals("0.0",usedYear)){
            usedYear = "0.1";
        }

        return usedYear;
    }

}
